package com.ohc.leetcode.二叉树.repect;

import com.ohc.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 2022年5月2日10:07:23
 */
public class 二叉树层序遍历01 {

    public static List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<List<Integer>> list = new ArrayList<>();
        while (!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> arrayList = new ArrayList<>();
            while (len > 0) {
                TreeNode node = queue.poll();
                arrayList.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
            list.add(arrayList);
        }

        return list;
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode();
        TreeNode treeNode2 = new TreeNode();
        TreeNode treeNode3 = new TreeNode();
        treeNode1.right = treeNode2;
        treeNode1.left = treeNode3;
        treeNode2.right = null;
        treeNode2.left = null;
        treeNode3.right = null;
        treeNode3.left = null;
        treeNode1.val = 1;
        treeNode2.val = 2;
        treeNode3.val = 3;
        List<List<Integer>> lists = levelOrder(treeNode1);
        System.out.println("lists = " + lists);
    }
}
